package com.nihome.entershopinfo.fragments;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.adapter.OpenTimeAdapter;
import com.nihome.entershopinfo.adapter.SysSpinnerAdapter;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.ImagePickDialog;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.request.ShopInfoReq;
import com.nihome.entershopinfo.entity.request.UploadImgReq;
import com.nihome.entershopinfo.entity.response.ExpandsLogRes;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.entity.response.UploadImgRes;
import com.nihome.entershopinfo.ui.HomePageActivity;
import com.nihome.entershopinfo.ui.PermissionsActivity;
import com.nihome.entershopinfo.utils.Base64Util;
import com.nihome.entershopinfo.utils.BitmapUtils;
import com.nihome.entershopinfo.utils.ImagePicker;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.NetUtil;
import com.nihome.entershopinfo.utils.PermissionsChecker;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.nihome.entershopinfo.utils.StringUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.IllegalFormatCodePointException;
import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by Carson on 2017/7/19.
 */
public class ShopInfoFragment extends Fragment implements View.OnClickListener, ImagePickDialog.DialogSelectedListener{
    private static final String TAG = "ShopInfoFragment";
    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private static final int REQUEST_PERMISSION = 100;  //权限请求
    private ImagePickDialog imagePickDialog;
    private ImagePicker mImagePicker;
    private Uri cameraUri;
    private Uri cutImgUri;
    private StringBuffer storeMenuIdBuff = new StringBuffer();

    private static final int PROVINCE      = 1000;
    private static final int CITY          = 1001;
    private static final int AREA          = 1002;

    private Context mContext;
    private Gson mGson;
    private User mUser;
    private NetUtil mNetUtil;
    private LoadingDialog dialog;

    private int selectType;
    private ExpandsLogRes expandsLog;

    private ShopInfoReq shopInfoReq;
    private String auditId;
    private short operation;

    private TextView shopInfoPrompt;
    private Spinner provinceSpinner;
    private Spinner citySpinner;
    private Spinner areaSpinner;
    private EditText detailAddressEdit;
    private EditText posNumberEdit;
    private EditText printNumberEdit;
    private LinearLayout eatLayout;
    private EditText teaFeeEdit;
    private Spinner teaFeeSpinner;
    private EditText tableNumberEdit;
    private EditText memoEdit;
    private Spinner takeNotifySpinner;
    private Spinner businessWaySpinner;
    private ImageView folderImg;
    private ImageView shopMenuBtn;
    private EditText menuMemoEdit;
    private EditText phoneTypeEdit;
    private LinearLayout openTimeLayout;
    private ImageView addOpenTime;
    private ImageView delOpenTime;
    private TextView shopInfoBack;
    private TextView goNextBtn;


    private LinearLayout payWayLayout;
    private Spinner payWaySpinner;


    private SysSpinnerAdapter provinceAdapter;
    private SysSpinnerAdapter cityAdapter;
    private SysSpinnerAdapter areaAdapter;
    private String[] provinceStr;
    private String[] cityStr;
    private String[] areaStr;
    private OpenTimeAdapter openTimeAdapter;


    private String selectProvince;
    private String selectCity;
    private String selectArea;


    private int businessWay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mGson = new Gson();
        mNetUtil = new NetUtil(mContext);
        mUser = SysApplication.getInstance().getmUser();
        mPermissionsChecker = new PermissionsChecker(mContext);
        openTimeAdapter = new OpenTimeAdapter(mContext);
        dialog = new LoadingDialog(mContext);
        selectType = getArguments().getInt(Constants.SELECT_TYPE);
        expandsLog = getArguments().getParcelable(Constants.DATA);
        auditId = SysApplication.getInstance().getAuditId();
        if (expandsLog.getStoreInfoResponseDTO() == null) operation = Constants.NEW;
        else operation = Constants.UPDATE;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop_info, container, false);
        shopInfoPrompt = (TextView) view.findViewById(R.id.shop_info_prompt);
        provinceSpinner = (Spinner) view.findViewById(R.id.province_spinner);
        citySpinner = (Spinner) view.findViewById(R.id.city_spinner);
        areaSpinner = (Spinner) view.findViewById(R.id.area_spinner);
        detailAddressEdit = (EditText) view.findViewById(R.id.detail_address_edit);
        openTimeLayout = (LinearLayout) view.findViewById(R.id.open_time_layout);
        openTimeLayout.addView(openTimeAdapter.getView(0, null, openTimeLayout));
        delOpenTime = (ImageView) view.findViewById(R.id.del_open_time);
        addOpenTime = (ImageView) view.findViewById(R.id.add_open_time);
        posNumberEdit = (EditText) view.findViewById(R.id.pos_number_edit);
        printNumberEdit = (EditText) view.findViewById(R.id.print_number_edit);
        eatLayout = (LinearLayout) view.findViewById(R.id.eat_layout);
        teaFeeEdit = (EditText) view.findViewById(R.id.tea_fee_edit);
        teaFeeSpinner = (Spinner) view.findViewById(R.id.tea_fee_spinner);
        tableNumberEdit = (EditText) view.findViewById(R.id.table_number_edit);
        memoEdit = (EditText) view.findViewById(R.id.memo_edit);
        takeNotifySpinner = (Spinner) view.findViewById(R.id.take_notify_spinner);
        businessWaySpinner = (Spinner) view.findViewById(R.id.business_way_spinner);
        folderImg = (ImageView) view.findViewById(R.id.folder_img);
        shopMenuBtn = (ImageView) view.findViewById(R.id.shop_menu_btn);
        menuMemoEdit = (EditText) view.findViewById(R.id.menu_memo);
        phoneTypeEdit = (EditText) view.findViewById(R.id.phone_type_edit);
        shopInfoBack = (TextView) view.findViewById(R.id.shop_info_back);
        goNextBtn = (TextView) view.findViewById(R.id.shop_info_go_next);


        payWayLayout = (LinearLayout) view.findViewById(R.id.pay_way_layout);
        payWaySpinner = (Spinner) view.findViewById(R.id.pay_way_spinner);

        businessWaySpinner.setOnItemSelectedListener(new BusinessWaySpinnerItemSelect());
        addOpenTime.setOnClickListener(this);
        delOpenTime.setOnClickListener(this);
        shopMenuBtn.setOnClickListener(this);
        shopInfoBack.setOnClickListener(this);
        goNextBtn.setOnClickListener(this);
        init();
        if (operation == Constants.UPDATE) initData();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Log.e(TAG, "hidden======" + hidden);
        super.onHiddenChanged(hidden);
        if (!hidden) {
            storeMenuIdBuff = new StringBuffer();
            selectType = getArguments().getInt(Constants.SELECT_TYPE);
            expandsLog = getArguments().getParcelable(Constants.DATA);
            auditId = SysApplication.getInstance().getAuditId();
            if (expandsLog.getStoreInfoResponseDTO() == null) operation = Constants.NEW;
            else operation = Constants.UPDATE;
        }
        if (operation == Constants.NEW) viewInit();
        if (operation == Constants.UPDATE) initData();
    }

    private void init(){
        if (selectType == Constants.H5_TYPE && businessWaySpinner.getSelectedItemPosition() == 0) payWayLayout.setVisibility(View.VISIBLE);
        else payWayLayout.setVisibility(View.GONE);
        businessWay = HomePageActivity.TS;
        shopInfoPrompt.setText(Html.fromHtml(getString(R.string.basic_info_prompt)));
        setSpinner();
    }

    private void initData(){
        selectProvince = expandsLog.getStoreInfoResponseDTO().getProvince();
        selectCity = expandsLog.getStoreInfoResponseDTO().getCity();
        selectArea = expandsLog.getStoreInfoResponseDTO().getDistrict();
        int provinceIndex = 0, cityIndex = 0, areaIndex = 0;
        for (int index = 0; index < provinceStr.length; index++) {
            if (selectProvince.equals(provinceStr[index])) provinceIndex = index;
        }
        for (int index = 0; index < cityStr.length; index++) {
            if (selectCity.equals(cityStr[index])) cityIndex = index;
        }
        for (int index = 0; index < areaStr.length; index++) {
            if (selectArea.equals(areaStr[index])) areaIndex = index;
        }
        provinceSpinner.setSelection(provinceIndex);
        citySpinner.setSelection(cityIndex);
        areaSpinner.setSelection(areaIndex);
        detailAddressEdit.setText(expandsLog.getStoreInfoResponseDTO().getStoreAddress());

        openTimeLayout.removeAllViews();
        openTimeLayout.addView(openTimeAdapter.getView(0, null, openTimeLayout));
        String[] openTime = expandsLog.getStoreInfoResponseDTO().getStoreOpeningHour().split(";");
        for (int i = 1; i < openTime.length; i++) {
            openTimeLayout.addView(openTimeAdapter.getView(0, null, openTimeLayout));
        }

        TextView openView;
        TextView closeView;
        String[] time = null;
        for (int i = 0; i < openTime.length; i++) {
            time = openTime[i].split("-");
            openView = (TextView) openTimeLayout.getChildAt(i).findViewById(R.id.open_time_item);
            closeView = (TextView) openTimeLayout.getChildAt(i).findViewById(R.id.close_time_item);
            openView.setText(time[0]);
            closeView.setText(time[1]);
        }
        posNumberEdit.setText(expandsLog.getStoreInfoResponseDTO().getPosNumber().toString());
        printNumberEdit.setText(expandsLog.getStoreInfoResponseDTO().getReceiptNumber().toString());
        if (expandsLog.getStoreInfoResponseDTO().getDiningStyle() == 0) {
            businessWay = HomePageActivity.TS;
            businessWaySpinner.setSelection(0);
        } else if (expandsLog.getStoreInfoResponseDTO().getDiningStyle() == 1) {
            businessWay = HomePageActivity.WM;
            businessWaySpinner.setSelection(1);
        } else if (expandsLog.getStoreInfoResponseDTO().getDiningStyle() == 2) {
            businessWay = HomePageActivity.TS_WM;
            businessWaySpinner.setSelection(2);
        }
        if (expandsLog.getStoreInfoResponseDTO().getDiningStyle() == 0 || expandsLog.getStoreInfoResponseDTO().getDiningStyle() == 2){
            teaFeeEdit.setText(expandsLog.getStoreInfoResponseDTO().getTeeFee().toString());
            if (expandsLog.getStoreInfoResponseDTO().getTeeFeeDiscount() == 1) teaFeeSpinner.setSelection(1);
            else if (expandsLog.getStoreInfoResponseDTO().getTeeFeeDiscount() == 0) teaFeeSpinner.setSelection(0);
            tableNumberEdit.setText(expandsLog.getStoreInfoResponseDTO().getNumberOfSite().toString());
            memoEdit.setText(expandsLog.getStoreInfoResponseDTO().getSeatMemo());
            if (expandsLog.getStoreInfoResponseDTO().getTakeMealReminder() == 1) takeNotifySpinner.setSelection(1);
            else if (expandsLog.getStoreInfoResponseDTO().getTakeMealReminder() == 0) takeNotifySpinner.setSelection(0);
        }
        if (!StringUtils.isEmpty(expandsLog.getStoreInfoResponseDTO().getStoreMenuIds())) {
            String[] menuIds = expandsLog.getStoreInfoResponseDTO().getStoreMenuIds().split(",");
            if (menuIds != null && menuIds.length > 0) {
                folderImg.setVisibility(View.VISIBLE);
                for (int i = 0; i < menuIds.length ; i++) {
                    storeMenuIdBuff.append(menuIds[i] +",");
                }
            }
        }

        if (!StringUtils.isEmpty(expandsLog.getStoreInfoResponseDTO().getStoreMenuMemo())){
            menuMemoEdit.setText(expandsLog.getStoreInfoResponseDTO().getStoreMenuMemo());
        }
        phoneTypeEdit.setText(expandsLog.getStoreInfoResponseDTO().getMobileModel());

        if (selectType == Constants.H5_TYPE && businessWaySpinner.getSelectedItemPosition() == 0) {
            payWayLayout.setVisibility(View.VISIBLE);
            payWaySpinner.setSelection(expandsLog.getStoreInfoResponseDTO().getHallEatPayType());
        } else {
            payWayLayout.setVisibility(View.GONE);
        }

    }

    void viewInit(){
        provinceSpinner.setSelection(0);
        citySpinner.setSelection(0);
        areaSpinner.setSelection(0);
        selectProvince = provinceStr[0];
        selectCity = cityStr[0];
        selectArea = areaStr[0];
        detailAddressEdit.setText("");
        openTimeLayout.removeAllViews();
        openTimeLayout.addView(openTimeAdapter.getView(0, null, openTimeLayout));
        posNumberEdit.setText("1");
        printNumberEdit.setText("2");
        businessWaySpinner.setSelection(0);
        businessWay = HomePageActivity.TS;
        teaFeeEdit.setText("");
        teaFeeSpinner.setSelection(0);
        tableNumberEdit.setText("");
        memoEdit.setText("");
        takeNotifySpinner.setSelection(0);
        folderImg.setVisibility(View.GONE);
        storeMenuIdBuff = new StringBuffer();
        menuMemoEdit.setText("");
        phoneTypeEdit.setText("");
        if (selectType == Constants.H5_TYPE && businessWaySpinner.getSelectedItemPosition() == 0) {
            payWayLayout.setVisibility(View.VISIBLE);
            payWaySpinner.setSelection(0);
        } else {
            payWayLayout.setVisibility(View.GONE);
        }

    }




    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_open_time:
                openTimeLayout.addView(openTimeAdapter.getView(0, null, openTimeLayout));
                break;
            case R.id.del_open_time:
                if (openTimeLayout.getChildCount() > 1) {
                    openTimeLayout.removeViewAt(openTimeLayout.getChildCount() - 1);
                }
                break;
            case R.id.shop_menu_btn:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                        startPermissionsActivity();
                    } else {
                        showDialog();
                    }
                } else {
                    showDialog();
                }
                break;
            case R.id.shop_info_back:
                ((HomePageActivity)getActivity()).backClick();
                break;
            case R.id.shop_info_go_next:
                //((HomePageActivity)getActivity()).goNextOfShopInfo(businessWay);
                if (!mNetUtil.isNetConnected()) {
                    Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (check()) subShopInfo();
                else Toast.makeText(mContext, getString(R.string.submit_prompt), Toast.LENGTH_SHORT).show();
                break;
        }
    }


    private void showDialog(){
        if (imagePickDialog == null) imagePickDialog = new ImagePickDialog(mContext);
        imagePickDialog.setDialogSelectedListener(this);
        imagePickDialog.show();
    }



    private String getOpenTime(){
        String openTime = "";
        TextView openView;
        TextView closeView;
        int count = openTimeLayout.getChildCount();
        for (int i = 0; i < count; i ++){
            openView = (TextView) openTimeLayout.getChildAt(i).findViewById(R.id.open_time_item);
            closeView = (TextView) openTimeLayout.getChildAt(i).findViewById(R.id.close_time_item);
            openTime += openView.getText().toString() + "-" + closeView.getText().toString();
            if (i != count - 1) openTime += ";";
        }
        return openTime;
    }



    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(getActivity(), REQUEST_PERMISSION,
                PERMISSIONS);
    }


    private Boolean check(){
        String checkOpenTime;
        String checkCloseTime;
        if (selectArea.equals(areaStr[0])) return false;
        if (StringUtils.isEmpty(detailAddressEdit.getText().toString())) return false;
        int count = openTimeLayout.getChildCount();
        for (int i = 0; i < count; i ++){
            checkOpenTime = ((TextView) openTimeLayout.getChildAt(i).findViewById(R.id.open_time_item)).getText().toString();
            checkCloseTime = ((TextView) openTimeLayout.getChildAt(i).findViewById(R.id.close_time_item)).getText().toString();
            if (StringUtils.isEmpty(checkOpenTime)) return false;
            if (StringUtils.isEmpty(checkCloseTime)) return false;
        }
        if (StringUtils.isEmpty(posNumberEdit.getText().toString())) return false;
        if (StringUtils.isEmpty(printNumberEdit.getText().toString())) return false;
        if (businessWay == HomePageActivity.TS || businessWay == HomePageActivity.TS_WM) {
            if (StringUtils.isEmpty(teaFeeEdit.getText().toString())) return false;
            if (StringUtils.isEmpty(tableNumberEdit.getText().toString())) return false;
        }
        if (StringUtils.isEmpty(storeMenuIdBuff.toString()) && StringUtils.isEmpty(menuMemoEdit.getText().toString())) return false;
        if (StringUtils.isEmpty(phoneTypeEdit.getText().toString())) return false;
        return true;
    }

    private void subShopInfo(){
        dialog.show(getString(R.string.load_text));
        shopInfoReq = new ShopInfoReq();
        shopInfoReq.setAuditId(auditId);
        shopInfoReq.setMarketerId(mUser.getUserId());
        shopInfoReq.setOperation(operation);
        shopInfoReq.setProvince(selectProvince);
        shopInfoReq.setCity(selectCity);
        shopInfoReq.setDistrict(selectArea);
        shopInfoReq.setStoreAddress(detailAddressEdit.getText().toString());
        shopInfoReq.setStoreOpeningHour(getOpenTime());
        shopInfoReq.setPosNumber(Integer.valueOf(posNumberEdit.getText().toString()));
        shopInfoReq.setReceiptNumber(Integer.valueOf(printNumberEdit.getText().toString()));
        shopInfoReq.setDiningStyle((short) businessWaySpinner.getSelectedItemPosition());
        if (selectType == Constants.H5_TYPE && businessWaySpinner.getSelectedItemPosition() == 0) {
            shopInfoReq.setHallEatPayType(payWaySpinner.getSelectedItemPosition());
        }
        if (businessWay == HomePageActivity.TS || businessWay == HomePageActivity.TS_WM) {
            String teaFee = teaFeeEdit.getText().toString();
            shopInfoReq.setTeeFee(new BigDecimal(teaFee).setScale(2, BigDecimal.ROUND_HALF_UP));
            shopInfoReq.setTeeFeeDiscount((short)teaFeeSpinner.getSelectedItemPosition());
            shopInfoReq.setNumberOfSite(Integer.valueOf(tableNumberEdit.getText().toString()));
            shopInfoReq.setSeatMemo(memoEdit.getText().toString());
            shopInfoReq.setTakeMealReminder((short)takeNotifySpinner.getSelectedItemPosition());
        }

        if (storeMenuIdBuff.length() > 0) shopInfoReq.setStoreMenuIds(storeMenuIdBuff.toString());
        if (!StringUtils.isEmpty(menuMemoEdit.toString())) shopInfoReq.setStoreMenuMemo(menuMemoEdit.getText().toString());
        shopInfoReq.setMobileModel(phoneTypeEdit.getText().toString());
        Log.e(TAG, "subShopInfo json = " + mGson.toJson(shopInfoReq));
        OkHttpUtils.postString().url(RequestAPI.SHOP_INFO_URL)
                .content(new Gson().toJson(shopInfoReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new ShopInfoCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG, e + "");
                        dialog.dismiss();
                        if (e instanceof UnknownHostException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof SocketException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (e instanceof IOException) {
                            Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBase<String> response, int id) {
                        dialog.dismiss();
                        switch (Integer.valueOf(response.getResultCode())) {
                            case Constants.REQ_SUCCESS:
                                expandsLog.setStoreInfoResponseDTO(shopInfoReq);
                                ((HomePageActivity)getActivity()).goNextOfShopInfo(businessWay);
                                break;
                            default:
                                Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
        });

    }

    abstract class ShopInfoCallback extends Callback<ResponseBase<String>> {
        @Override
        public ResponseBase<String> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<String>>(){}.getType();
            ResponseBase<String> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }



    /** 上传图片 */
    private void uploadImgService(){
        dialog.show(getString(R.string.load_text));
        Log.e(TAG, "image path = " + cutImgUri.getPath());
        String img = "data:image/png;base64,";
        img +=  Base64Util.encode(BitmapUtils.FileTobyte(new File(cutImgUri.getPath())));
        //String img =  Base64Util.encode(BitmapUtils.FileTobyte(new File(cutImgUri.getPath())));
        UploadImgReq uploadImgReq = new UploadImgReq();
        uploadImgReq.setFileBase64Data(img);
        uploadImgReq.setUserId(mUser.getUserId());
        OkHttpUtils.postString().url(RequestAPI.UPLOAD_IMG_URL)
                .content(new Gson().toJson(uploadImgReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new UploadImgCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e + "");
                dialog.dismiss();
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<UploadImgRes> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        Toast.makeText(mContext, getString(R.string.upload_success), Toast.LENGTH_SHORT).show();
                        if (folderImg.getVisibility() == View.GONE)  folderImg.setVisibility(View.VISIBLE);
                        storeMenuIdBuff.append(response.getResult().getFileId() +",");
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class UploadImgCallback extends Callback<ResponseBase<UploadImgRes>> {
        @Override
        public ResponseBase<UploadImgRes> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<UploadImgRes>>(){}.getType();
            ResponseBase<UploadImgRes> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }


    private void setSpinner(){
        provinceStr = getResources().getStringArray(R.array.province);
        cityStr = getResources().getStringArray(R.array.city);
        areaStr = getResources().getStringArray(R.array.area_gz);
        selectProvince = provinceStr[0];
        selectCity = cityStr[0];
        selectArea = areaStr[0];

        provinceAdapter = new SysSpinnerAdapter(mContext, provinceStr);
        provinceSpinner.setAdapter(provinceAdapter);
        provinceSpinner.setSelection(0, true);
        provinceSpinner.setOnItemSelectedListener(new CitySpinnerItemSelect(PROVINCE));

        cityAdapter = new SysSpinnerAdapter(mContext, cityStr);
        citySpinner.setAdapter(cityAdapter);
        citySpinner.setSelection(0, true);
        citySpinner.setOnItemSelectedListener(new CitySpinnerItemSelect(CITY));

        areaAdapter = new SysSpinnerAdapter(mContext, areaStr);
        areaSpinner.setAdapter(areaAdapter);
        areaSpinner.setSelection(0, true);
        areaSpinner.setOnItemSelectedListener(new CitySpinnerItemSelect(AREA));
    }


    class CitySpinnerItemSelect implements AdapterView.OnItemSelectedListener{
        private int type;
        public CitySpinnerItemSelect(int type){
            this.type = type;
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (type) {
                case PROVINCE:
                    selectProvince = provinceSpinner.getSelectedItem().toString();
                    break;
                case CITY:
                    if (position == 0) areaStr = getResources().getStringArray(R.array.area_gz);
                    if (position == 1) areaStr = getResources().getStringArray(R.array.area_fs);
                    if (position == 2) areaStr = getResources().getStringArray(R.array.area_sz);
                    if (position == 3) areaStr = getResources().getStringArray(R.array.area_dg);
                    areaAdapter.setData(areaStr);
                    areaAdapter.notifyDataSetChanged();
                    areaSpinner.setSelection(0, true);
                    selectCity = citySpinner.getSelectedItem().toString();
                    break;
                case AREA:
                    selectArea = areaSpinner.getSelectedItem().toString();
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    class BusinessWaySpinnerItemSelect implements AdapterView.OnItemSelectedListener{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (selectType == Constants.H5_TYPE && businessWaySpinner.getSelectedItemPosition() == 0) payWayLayout.setVisibility(View.VISIBLE);
            else payWayLayout.setVisibility(View.GONE);
            if (position == 0) {
                businessWay = HomePageActivity.TS;
                eatLayout.setVisibility(View.VISIBLE);
            }
            if (position == 1) {
                businessWay = HomePageActivity.WM;
                eatLayout.setVisibility(View.GONE);
            }
            if (position == 2) {
                businessWay = HomePageActivity.TS_WM;
                eatLayout.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    @Override
    public void onPhone() {
        Log.e(TAG, "相册........");
        if (mImagePicker == null) mImagePicker = new ImagePicker(getActivity(), this);
        mImagePicker.pickOnphone();
    }

    @Override
    public void onCapture() {
        Log.e(TAG, "拍照........");
        if (mImagePicker == null) mImagePicker = new ImagePicker(getActivity(), this);
        cameraUri = mImagePicker.openCamera();
        Log.e(TAG, "onCapture URI = " + cameraUri);
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case ImagePicker.REQUEST_CAPTURE:
                    cutImgUri = mImagePicker.cropPhoto(cameraUri);
                    break;
                case ImagePicker.REQUEST_PICK_IMAGE:
                    cameraUri = data.getData(); //获取系统返回的照片的Uri
                    cutImgUri = mImagePicker.cropPhoto(cameraUri);
                    break;
                case ImagePicker.REQUEST_PICTURE_CUT:
                    if (!mNetUtil.isNetConnected()) {
                        Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    uploadImgService();
                    break;
            }
        }
    }
}
